#!/bin/bash
# 采用 XY_MBA32A 模组作为蓝牙通讯。
# 采用 pipe 与bj_timer 主程序进行进程间通讯。


# 定义管道名称
read_path="/tmp/motor_pipe.in"
write_path="/tmp/motor_pipe.out"

# 光耦状态文件
bj_sensor_status_path="/home/bj/tmp/gpio_status.txt"

DEVICE="/dev/ttyUSB0"
USER="bj"

client_mac=""

# 初始化全局变量
usb_audio_found=false

create_pipe() {
    # 检查管道是否存在
    if [ -p "$read_path" ] || [ -e "$read_path" ]; then
        echo 1 |sudo -S rm -f "$read_path"
        echo "管道已删除: $read_path"
    else
        echo "管道不存在: $read_path"
    fi

    if [ -p "$write_path" ] || [ -e "$write_path" ]; then
        echo 1 |sudo -S rm -f "$write_path"
        echo "管道已删除: $write_path"
    else
        echo "管道不存在: $write_path"
    fi

    # 检查管道是否存在
    if [ ! -p "${read_path}" ]; then
        # 创建命名管道
        mkfifo "${read_path}"
        echo "管道已创建: ${read_path}"
    else
        echo "管道已存在: ${read_path}"
    fi

    if [ ! -p "${write_path}" ]; then
        # 创建命名管道
        mkfifo "${write_path}"
        echo "管道已创建: ${write_path}"
    else
        echo "管道已存在: ${write_path}"
    fi
}

ble_scan() {
    # 扫描蓝牙 4.0 BLE  
    while true; do
        echo "AT+SCAN=1" > $DEVICE
        # 尝试读取数据
        while IFS= read -t 2 line < $DEVICE; do
            echo "接收到的数据: $line"
            result=$(echo "$line" | grep "BJ_TIMER" | awk '{print $1}')
            # 打印结果
            if [ -n "$result" ]; then
                client_mac=$result
                echo "提取到的数据: $client_mac"
            fi
        done

        if [ "$client_mac" != "" ]
        then
            break
        fi

        sleep 1
    done

    echo "scan finished $client_mac"
}

ble_connect() {
    if [ "$client_mac" = "" ]
    then
        return
    fi

    while true; do
        echo "AT+CONN=${client_mac},0" > ${DEVICE}
        read -t 2 line < $DEVICE
        echo "接收: $line"

        if [ "$line" != "ERROR" ]
        then
            echo "蓝牙连接成功"
            break
        fi

        # sleep 1
    done
}

ble_auto_mac() {
    # 保存自动重连 MAC
    while true; do
        echo "AT+AUTO_MAC=${client_mac},0" > ${DEVICE}
        read -t 1 line < $DEVICE
        echo "接收: $line"

        if [ "$line" != "ERROR" ]
        then
            echo "设置保存自动重连 MAC成功"
            break
        fi
        sleep 1
    done

    return
}

ble_auto_cfg() {
    # 设置自动重连
    while true; do
        echo "AT+AUTO_CFG=1" > ${DEVICE}
        read -t 1 line < $DEVICE
        echo "接收: $line"

        if [ "$line" != "ERROR" ]
        then
            echo "设置自动重连成功"
            break
        fi

        sleep 1
    done

    return
}

ble_auto_del() {
    # 删除自动重连列表
    while true; do
        echo "AT+AUTO_DEL" > ${DEVICE}
        read line < $DEVICE
        echo "接收: $line"

        if [ "$line" != "ERROR" ]
        then
            echo "删除自动重连列表成功"
            break
        fi
        sleep 1
    done

    return
}

initialize_device() {
    while [ ! -e "$DEVICE" ]; do
        echo "Device $DEVICE not found. Waiting..."
        sleep 1
    done

    # 修改设备权限
    echo 1 | sudo -S chown $USER $DEVICE

    # 设置串口参数 -echo 关闭回显功能
    stty -F "$DEVICE" 115200 cs8 -parenb -cstopb cread clocal -echo
    echo "Device $DEVICE initialized."

    # 查询蓝牙连接状态
    echo "AT+DEV?" > $DEVICE
    read line < $DEVICE
    echo "接收: $line"
    if [ "$line" = "+DEV:" ] 
    then
        echo "未连接蓝牙设备"
        # 删除自动重连列表
        ble_auto_del
        sleep 1
        # 扫描蓝牙
        ble_scan
        sleep 1
        # 连接蓝牙
        ble_connect
        sleep 1
        # 保存自动重连 MAC
        ble_auto_mac
        sleep 1
        # 设置自动重连
        ble_auto_cfg
    else
        dev_msg=$(echo $line | awk -F: '{print $2}')
        echo "已连接蓝牙设备"
    fi
}





# 检测usb  音频设备是否存在
usb_audio_scan() {
    USB_DEVICE="/dev/ttyUSB0"

    echo "USB_DEVICE:${USB_DEVICE}"

    while true; do
        # 检查 USB 音频设备是否存在
        if arecord -l | grep -q -i "USB Audio"; then
            # 判断 device_found 状态
            # echo "设备已找到。 $usb_audio_found"

            if [ "$usb_audio_found" = false ]; then
                echo "signal blink cmd"
                # 修改设备权限
                echo 1 | sudo -S chown bj $USB_DEVICE

                # 设置串口参数 -echo 关闭回显功能
                stty -F "$USB_DEVICE" 115200 cs8 -parenb -cstopb cread clocal -echo
                echo "Device $USB_DEVICE initialized."

                while true; do
                    echo -ne '\x5A\xA5\x01\x22' > "$USB_DEVICE"  # 信号灯闪烁
                    read -t 2 line < "$USB_DEVICE"
                    echo "接收: $line"

                    # if [ "$line" = "\xA5\x5A\x01\x01" ]
                    if [ "$line" = "A55A0101" ]; then
                        echo "open 控制成功"
                        usb_audio_found=true
                        break
                    fi
                done
            fi
        else
            # echo "未找到 USB 音频设备。"
            if [ "$usb_audio_found" = true ]; then

                while true; do
                    echo -ne '\x5A\xA5\x01\x23' > "$USB_DEVICE" # 信号灯停止闪烁
                    read -t 2 line < "$USB_DEVICE"
                    echo "接收: $line"
                    if [ "$line" = "A55A0101" ]; then
                        echo "close 控制成功"
                        usb_audio_found=false
                        break
                    fi
                done
            fi
        fi

        sleep 3
    done
}

# 读取光耦状态
read_opt_status(){
    USB_DEVICE="/dev/ttyUSB0"
    echo "read_opt_status:${USB_DEVICE}"

    while true; do
        echo -ne '\x5A\xA5\x01\x30' > ${USB_DEVICE}  # 读取光耦状态
        read -t 0.1 line < ${USB_DEVICE}
        # echo "接收: $line"

        if [ "${line:0:6}" = "A55A05" ]; then
            last_five_bytes="${line: -5}"
            echo "后5个字节: $last_five_bytes"
            # echo "$last_five_bytes" > "$bj_sensor_status_path"
            printf "%s" "$last_five_bytes" > "$bj_sensor_status_path"
        fi

        sleep 0.5
    done
}


# 创建管道
create_pipe

while true; do
    initialize_device

    # 启动 usb_audio_scan 并记录其 PID
    usb_audio_scan &
    scan_pid=$!

    echo "enter device deamon..."
    # 检查设备是否存在
    while [ -e "$DEVICE" ]; do
        # 进入通讯状态
        if read -t 1 line < $read_path; then
            echo "读取到的数据: $line"
            case $line in
                "CH")
                echo "recv CH"
                echo -ne '\x5A\xA5\x01\x0C' > ${DEVICE}
                ;;

                "CB")
                echo "recv CB"
                echo -ne '\x5A\xA5\x01\xCB' > ${DEVICE}
                ;;

                "9H")
                echo "recv 9H"
                echo -ne '\x5A\xA5\x01\x09' > ${DEVICE}
                ;;

                "6H")
                echo "recv 6H"
                echo -ne '\x5A\xA5\x01\x06' > ${DEVICE}
                ;;

                "3H")
                echo "recv 3H"
                echo -ne '\x5A\xA5\x01\x03' > ${DEVICE}
                ;;

                "12H")
                echo "recv 12H"
                echo -ne '\x5A\xA5\x01\x12' > ${DEVICE}
                ;;

                "20R")
                echo "recv 20R"
                # echo -ne '\x5A\xA5\x01\x12' > ${DEVICE}
                ;;

                # 运行指示灯关
                "20R0")
                echo "recv 20R0"
                echo -ne '\x5A\xA5\x01\x20' > ${DEVICE}
                ;;

                # 运行指示灯开
                "20R1")
                echo "recv 20R1"
                echo -ne '\x5A\xA5\x01\x21' > ${DEVICE}
                ;;

                # 信号灯闪烁
                "21S")
                echo "recv 21S"
                echo -ne '\x5A\xA5\x01\x22' > ${DEVICE}
                ;;

                # 信号灯停止闪烁
                "21S0")
                echo "recv 21S0"
                echo -ne '\x5A\xA5\x01\x23' > ${DEVICE}
                ;;

                # 停止实时读取光耦传感器
                "30R1")
                echo "开始读取光耦"
                read_opt_status &
                read_opt_pid=$!
                ;;

                # 开始实时读取光耦传感器
                "30R0")
                echo "停止读取光耦"
                kill "$read_opt_pid"
                ;;


            esac
        else
            echo "读取超时或管道为空。"
        fi

    done

    # 停止 usb_audio_scan 进程
    kill "$scan_pid"


    echo "Device $DEVICE removed. Reinitializing..."
done

